package com.shareyi.jdwork.tree;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeParser {


    public static TreeElement parseTreeStruct(List<TreeElement> treeElementList){
        TreeElement rootElement=null;
        Map<Long,TreeElement> treeElementMap=new HashMap<Long, TreeElement>();
        for(TreeElement treeElement:treeElementList){
            treeElementMap.put(treeElement.getId(),treeElement);
            if(treeElement.getParentId()==null || treeElement.getParentId()==-1){
                rootElement=treeElement;
            }
        }

        for(TreeElement treeElement:treeElementList){
            if(treeElement==rootElement){
                continue;
            }
            Long parentId=treeElement.getParentId();
            TreeElement parent=treeElementMap.get(parentId);
            if(parent==null){
                //TODO 加警告日志
                continue;
            }
            parent.addChild(treeElement);
        }

        return rootElement;
    }


    public static void main(String[] args) throws Exception {
        InputStream inputStream = TreeParser.class.getClassLoader().
                getResourceAsStream("file/tree.json");
        String treeJson=IOUtils.toString(inputStream, Charsets.UTF_8);
        List<TreeElement> treeList= JSON.parseArray(treeJson,TreeElement.class);
        TreeElement treeStruct = parseTreeStruct(treeList);
        System.out.println(treeStruct);
    }

}
